package library.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import library.commands.CommandManager;

public class ClientSocketThread extends Thread {

    private Socket sock;

    public ClientSocketThread(Socket sock) {
        this.sock = sock;
    }

    @Override
    public void run() {
        listen();
        CommandManager.getInstance().removeSession(sock);
    }

    private void listen() {
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            ois = new ObjectInputStream(sock.getInputStream());
            oos = new ObjectOutputStream(sock.getOutputStream());
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            return;
        }
        while (true) {
            String command = null;
            try {
                command = (String) ois.readObject();
            } catch (IOException ioe) {
                break;
            } catch (ClassNotFoundException cnfe) {
            }
            System.out.println("Command is " + command);
            try {
                CommandManager.getInstance().execute(command, sock, ois, oos);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}